package com.lc.index.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.lc.common.utils.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 自动处理参数，需要正在对应实体上加fill参数
 */
@Component
public class MybatisMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        String userName;
        try {
            userName = SecurityUtils.getUsername();
        } catch (Exception e) {
            userName = "-";
        }
        // 判断是否存在createBy
        if (metaObject.hasSetter("createBy")) {
            setFieldValByName("createBy", userName, metaObject);
        }
        if (metaObject.hasSetter("updateBy")) {
            setFieldValByName("updateBy", userName, metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String userName;
        try {
            userName = SecurityUtils.getUsername();
        } catch (Exception e) {
            userName = "-";
        }
        if (metaObject.hasSetter("updateBy")) {
            setFieldValByName("updateBy", userName, metaObject);
        }
        if (metaObject.hasSetter("updateTime")) {
            setFieldValByName("updateTime", new Date(), metaObject);
        }
    }
}
